import path from "node:path";

import react from "@vitejs/plugin-react";
import { visualizer } from "rollup-plugin-visualizer";
import { defineConfig, loadEnv } from "vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import tsconfigPaths from "vite-tsconfig-paths";

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
	const env = loadEnv(mode, process.cwd(), "");
	const base = env.VITE_APP_BASE_PATH || "/";
	const isProduction = mode === "production";

	return {
		base,
		plugins: [
			react(),
			tsconfigPaths(),
			createSvgIconsPlugin({
				iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
				symbolId: "icon-[dir]-[name]",
			}),
			isProduction &&
				visualizer({
					open: true,
					gzipSize: true,
					brotliSize: true,
				}),
		],
		server: {
			open: false,
			host: true,
			port: 3001,
			proxy: {
				"/api": {
					target: "https://www.chuangmeng888.com",
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, "/api"),
					secure: false,
					ws: true,
				},
			},
		},
		optimizeDeps: {
			include: ["react", "react-dom", "react-router", "antd"],
		},
		esbuild: {
			drop: isProduction ? ["console", "debugger"] : [],
			legalComments: "none",
			ignoreAnnotations: true,
			tsconfigRaw: {
				compilerOptions: {
					noUnusedLocals: false,
					noUnusedParameters: false,
					ignoreDeprecations: "5.0",
					suppressImplicitAnyIndexErrors: true,
				},
			},
			treeShaking: true,
			jsx: "automatic",
			jsxFactory: "React.createElement",
			jsxFragment: "React.Fragment",
			define: {
				"process.env.NODE_ENV": JSON.stringify(
					isProduction ? "production" : "development",
				),
			},
		},
		build: {
			target: "esnext",
			minify: "esbuild",
			sourcemap: false,
			cssCodeSplit: true,
			chunkSizeWarningLimit: 0,
			reportCompressedSize: false,
			terserOptions: {
				compress: {
					drop_console: true,
					drop_debugger: true,
				},
			},
			commonjsOptions: {
				transformMixedEsModules: true,
			},
			rollupOptions: {
				onwarn: (warning, warn) => {
					if (warning.code === "CIRCULAR_DEPENDENCY") return;
					if (warning.code === "UNUSED_EXTERNAL_IMPORT") return;
					warn(warning);
				},
				output: {
					manualChunks: {
						"vendor-react": ["react", "react-dom", "react-router"],
						"vendor-antd": ["antd", "@ant-design/icons", "@ant-design/cssinjs"],
						"vendor-charts": ["apexcharts", "react-apexcharts"],
						"vendor-utils": ["axios", "dayjs", "i18next", "zustand"],
						"vendor-ui": [
							"framer-motion",
							"styled-components",
							"@iconify/react",
						],
					},
				},
			},
		},
	};
});
